package com.ruoyi.wx.service.imp;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.goods.utils.GetOrder;
import com.ruoyi.utils.IpUtil;
import com.ruoyi.wx.service.WXPayService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author X
 * @version 1.0
 * @ClassName WXPayServiceImpl
 * @description
 * @date 2020/11/10
 **/
@Service
public class WXPayServiceImpl implements WXPayService {

    private static final String notify_url = "http://zs.91gongju.cn:10003/wx/pay/notify";

    @Autowired
    private WXPay wxPay;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;

    @Override
    public Map nativePay(Map<String, String> parameterMap, HttpServletRequest request) {
        String token = tokenService.getToken(request);
        Claims claims = tokenService.parseToken(token);
        // 解析对应的权限以及用户信息
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = tokenService.getTokenKey(uuid);
        // 获取到用户信息
        LoginUser loginUser = redisCache.getCacheObject(userKey);
        //获取用id
        Long userId = loginUser.getUser().getUserId();
        try {
            HashMap<String, String> paramMap = new HashMap<>();
            /***
             * 参数
             */
            paramMap.put("attach", String.valueOf(userId));
            paramMap.put("appid", "wx50b8f1d6623c060d");
            paramMap.put("mch_id", "1431813202");
            //随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //商品描述
            paramMap.put("body", parameterMap.get("body"));
            //商户订单号
            paramMap.put("out_trade_no", GetOrder.getOrderNo());
            //总金额
            paramMap.put("total_fee", parameterMap.get("money"));
            //终端IP
            paramMap.put("spbill_create_ip", IpUtil.getIpAddr(request));
            //通知地址
            paramMap.put("notify_url", notify_url);
            //交易类型
            paramMap.put("trade_type", "NATIVE");
            String sign = WXPayUtil.generateSignature(paramMap, "wmdtfyndmsxyyndgllyndzyfxzrjrtzt");
            paramMap.put("sign", sign);

            //基于wxpay完成统一下单接口的调用,并获取返回结果
            Map<String, String> result = wxPay.unifiedOrder(paramMap);
            //获取返回的数据
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * codeUrl
     * @param codeUrl
     * @return
     */
    @Override
    public BitMatrix getQR(String codeUrl) throws WriterException {
        Map<EncodeHintType, Object> encode = new HashMap<>();
        encode.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        encode.put(EncodeHintType.CHARACTER_SET, "UFT-8");
        BitMatrix matrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 400, 400);
        return matrix;
    }

    @Override
    public Map queryOrder(String orderId) {
        try {
            Map<String, String> map = new HashMap();
            map.put("out_trade_no", orderId);
            Map<String, String> resultMap = wxPay.orderQuery(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
